<?php

class authenticationActions extends sfActions {

    public function executeLogin(sfWebRequest $request){
        $username = $request->getParameter('username');
        $password = $request->getParameter('password');

        $c = new Criteria();
        $c->add(UserPeer::USERNAME, $username);
        $c->add(UserPeer::PASSWORD, $password);
        $user = UserPeer::doSelectOne($c);
        if(is_object($user)){
            $this->getUser()->setAuthenticated(true);
            $this->getUser()->setAttribute('current_user', $user);
            $this->redirect('@dashboard');
        }else{
            $this->getUser()->setFlash('msg','incorrecto');
            $this->redirect('@homepage');
        }
    }

    public function executeLogout(sfWebRequest $request){
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->getAttributeHolder()->remove('current_user');
        $this->redirect('@homepage');
    }

    public function executeLogin_with(sfWebRequest $request){
        /* provider: "Google", "Facebook", etc... */
        $provider = @trim(strip_tags($request->getParameter('provider')));
        
        $myLib = new myLib();
        $myGoogleAnalytics = new myGoogleAnalytics();
        
        $myLib->validateAuthentication($provider);

        if($provider=="Google"){
            $hybridauth = new Hybrid_Auth($myLib->getHybridAuthConfig());
            $adapter = $hybridauth->getAdapter("Google");
            $access_token = $adapter->getAccessToken();

            $current_user = $this->getUser()->getAttribute('current_user');
            $myGoogleAnalytics->saveRefreshToken($current_user, $access_token["refresh_token"]);

            $this->getUser()->addCredential("Google");
        }else if($provider=="Facebook"){
            $this->getUser()->addCredential("Facebook");
        }else if($provider=="Twitter"){
            $this->getUser()->addCredential("Twitter");
        }

        $this->redirect('@dashboard');

    }

    public function executeLogout_from(sfWebRequest $request){
        /* provider: "Google", "Facebook", etc... */
        $provider = @trim(strip_tags($request->getParameter('provider')));

        $myLib = new myLib();
        $hybridauth = new Hybrid_Auth($myLib->getHybridAuthConfig());

        // call back the requested provider adapter instance
        $adapter = $hybridauth->getAdapter($provider);

        // logout the user from provider
        $adapter->logout();

        $this->getUser()->removeCredential($provider);

        $this->redirect('@dashboard');
    }

    public function executeLogout_from_all(sfWebRequest $request){
        $myLib = new myLib();
        $hybridauth = new Hybrid_Auth($myLib->getHybridAuthConfig());

        $this->getUser()->setAuthenticated(false);
        $this->getUser()->getAttributeHolder()->clear();

        // logout the user from all providers
        $hybridauth->logoutAllProviders();

        $this->redirect('@homepage');
    }

}